<template>
  <div class="table-box">
    <Table ref="tableRef" row-key="id" :columns="columns" :request-api="clientApi.list">
      <template #header>
        <ElButton v-auth="'system:client:add'" type="primary" :icon="CirclePlus" @click="handleAdd">新增客户端</ElButton>
      </template>
      <!-- 菜单操作 -->
      <template #action="{ row, id }">
        <TableAction :actions="getActions(row, id)" :show-num="0"></TableAction>
      </template>
    </Table>
    <Dialog ref="dialogRef" @submit="handleSubmit" :title="title">
      <Form ref="formRef" :schemas="schemas" label-width="100px"></Form>
    </Dialog>
  </div>
</template>

<script setup lang="tsx" name="SysClient">
import { ref } from "vue";
import { ElButton } from "element-plus";
import { CirclePlus } from "@element-plus/icons-vue";
import { Table, TableAction, useTable } from "@/components/Table";
import { Dialog, useDialog } from "@/components/Dialog";
import { Form, useForm } from "@/components/Form";
import { ActionItem } from "@/components/Table/type";
import clientApi from "./api";
import { columns, schemas } from "./data";
const tableRef = ref();
const dialogRef = ref();
const formRef = ref();
const { getTableList } = useTable(tableRef);
const { open, close, openLoading } = useDialog(dialogRef);
const { updateFields, validateFields, resetFields } = useForm(formRef);
const title = ref("");
const handleAdd = () => {
  title.value = "新增客户端";
  open(0);
  resetFields();
};
const handleSubmit = async flag => {
  const fields = await validateFields();
  await openLoading(async () => {
    if (flag) {
      await clientApi.edit(fields);
    } else {
      await clientApi.add(fields);
    }
    close();
    await getTableList();
  });
};

const getActions = (row, id): Partial<ActionItem>[] => {
  return [
    {
      type: "primary",
      icon: "edit",
      auth: "system:client:edit",
      onClick: () => {
        title.value = "编辑客户端";
        dialogRef.value.open(1);
        updateFields(Object.assign({}, row));
      }
    },
    {
      type: "danger",
      auth: "system:client:remove",
      popConfirm: {
        onConfirm: async () => {
          await clientApi.remove(id);
          await getTableList();
        }
      },
      icon: "delete"
    }
  ];
};
</script>
